package com.seecoder.BlueWhale.serviceImpl.payStrategy;

import com.seecoder.BlueWhale.configure.AlipayTools;
import com.seecoder.BlueWhale.enums.CouponStatusEnum;
import com.seecoder.BlueWhale.enums.OrderStatusEnum;
import com.seecoder.BlueWhale.exception.BlueWhaleException;
import com.seecoder.BlueWhale.po.Commodity;
import com.seecoder.BlueWhale.po.Coupon;
import com.seecoder.BlueWhale.po.CouponGroup;
import com.seecoder.BlueWhale.po.Order;
import com.seecoder.BlueWhale.repository.*;
import com.seecoder.BlueWhale.serviceImpl.CouponGroupServiceImpl;
import com.seecoder.BlueWhale.util.SecurityUtil;
import com.seecoder.BlueWhale.vo.DiscountParams;
import com.seecoder.BlueWhale.vo.PayParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Primary
public class AlipayPay implements PayStrategy {
    @Autowired
    OrderRepository orderRepository;

    @Autowired
    CommodityRepository commodityRepository;

    @Autowired
    CouponRepository couponRepository;

    @Autowired
    SecurityUtil securityUtil;

    @Autowired
    CouponGroupRepository couponGroupRepository;

    @Autowired
    CouponGroupServiceImpl couponGroupServiceImpl;

    @Autowired
    AlipayTools alipayTools;

    @Override
    public boolean pay(PayParams params, HttpServletResponse httpServletResponse) {
        List<Integer> couponID = params.getCouponID();
        Order order = orderRepository.findById(params.getOrderID());

        if (order == null) {
            throw BlueWhaleException.orderNotFound();
        } else if (order.getStatus() != OrderStatusEnum.UNPAID) {
            throw BlueWhaleException.orderStatusWrong();           //订单状态异常
        }

        Commodity commodity = commodityRepository.findById(order.getCommodityID().intValue());
        double price= commodity.getPrice()*order.getQuantity();
        List<Coupon> coupons = couponID.stream().map(a -> couponRepository.findById(a.intValue())).collect(Collectors.toList());

        if (!couponID.isEmpty()) {
            if (coupons.stream().anyMatch( coupon-> {
                boolean flag = false;
                //使用过或不是自己的优惠券
                flag |= (coupon.getCouponStatus() == CouponStatusEnum.USED
                        || coupon.getUserId() != securityUtil.getUserId());
                CouponGroup couponGroup = couponGroupRepository.findById(coupon.getCouponGroupId());
                //不是全局且不是该商店的优惠券
                flag &= (couponGroup.getStoreId() != 0 && couponGroup.getStoreId() != order.getStoreID());
                return flag;
            })) {
                throw BlueWhaleException.invalidCoupon();
            } else {
                price=couponGroupServiceImpl.discount(new DiscountParams(price,coupons.stream().map(Coupon::getCouponGroupId).collect(Collectors.toList())));
            }
        }
        try {
            httpServletResponse.setContentType("text/html;charset=utf-8");
            httpServletResponse.getWriter().write(alipayTools.pay(order.getId().toString(),commodity.getName(), price,couponID));
            httpServletResponse.getWriter().flush();
            httpServletResponse.getWriter().close();
        } catch (IOException e){
            throw new BlueWhaleException(e.getMessage());
        }
        return true;
    }
}
